package com.cloud.bc.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.bc.mapper.BcSingleMatesMapper;
import com.cloud.bc.mapper.BcSinglesMapper;
import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.*;
import com.cloud.bc.model.enums.CookieConst;
import com.cloud.bc.model.request.NearbyRequest;
import com.cloud.bc.model.request.SingleListRequest;
import com.cloud.bc.model.request.VideoListRequest;
import com.cloud.bc.model.request.VoiceListRequest;
import com.cloud.bc.model.response.*;
import com.cloud.bc.service.*;
import com.cloud.common.security.AES;
import com.cloud.common.util.CookieUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 单身资料
 *
 * @author douhaichao code generator
 * @date 2021-01-03 19:27:34
 */
@Service
@AllArgsConstructor
public class BcSinglesServiceImpl extends ServiceImpl<BcSinglesMapper, BcSingles> implements BcSinglesService {

    private final BcCategorysService bcCategorysService;
    private final BcCategoryDistrictsService bcCategoryDistrictsService;
    private final BcSingleMatesMapper bcSingleMatesMapper;
    private final BcSetmealsService bcSetmealsService;
    private final BcSingleLocationsService bcSingleLocationsService;
    private final BcUsersService bcUsersService;


    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public BcSingles selectOne(BcSingles req) {
        QueryWrapper queryWrapper = new QueryWrapper<BcSingles>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<BcSingles> selectAll(BcSingles req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<BcSingles> selectPage(Page page, BcSingles req) {
        QueryWrapper<BcSingles> bcSinglesQueryWrapper = new QueryWrapper<>();
        bcSinglesQueryWrapper.setEntity(req);
        bcSinglesQueryWrapper.orderByDesc("browse");
        IPage<BcSingles> list = baseMapper.selectPage(
                page, bcSinglesQueryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(BcSingles req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public boolean setSingles(String key, String value, Integer userId) {
        String categoryCn = "";
        //如果是固定值（数据库不能维护的数据）
        if (key.contains("constellation") || key.contains("zodiac") || key.contains("blood")) {
            BcCategorys categoryById = bcCategorysService.getCategoryById(key, Convert.toInt(value));
            categoryCn = categoryById.getName();
        } else {
            categoryCn = getCategoryName(key, value);
        }
        categoryCn = StrUtil.isEmpty(categoryCn) ? "不限" : categoryCn;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        if (key.equals("video")) {
            //我的视频
            BcSingles bcSingles = new BcSingles();
            bcSingles.setVideo(value);
            bcSingles.setVideoCheck(3);
            baseMapper.update(bcSingles, queryWrapper);
        } else if (key.equals("voice")) {
            //我的声音
            BcSingles bcSingles = new BcSingles();
            bcSingles.setVoice(value);
            bcSingles.setVoiceCheck(3);
            baseMapper.update(bcSingles, queryWrapper);
        } else if (key.contains("mate_")) {
            //修改对方单身表
            BcSingleMates bcSingleMates = new BcSingleMates();
            if (key.equals("mate_gender")) {
                bcSingleMates.setMateGender(Convert.toInt(value, 0));
            }
            if (key.equals("mate_age")) {
                bcSingleMates.setMateAge(value);
                String[] split = StrUtil.split(value, "~");
                bcSingleMates.setMateAgeMin(Convert.toInt(split[0], 0));
                bcSingleMates.setMateAgeMax(Convert.toInt(split[1], 0));
            }
            if (key.equals("mate_height")) {
                bcSingleMates.setMateHeight(value);
                String[] split = StrUtil.split(value, "~");
                bcSingleMates.setMateHeightMin(Convert.toInt(split[0], 0));
                bcSingleMates.setMateHeightMax(Convert.toInt(split[1], 0));
            }
            if (key.equals("mate_weight")) {
                bcSingleMates.setMateWeight(value);
                String[] split = StrUtil.split(value, "~");
                bcSingleMates.setMateWeightMin(Convert.toInt(split[0], 0));
                bcSingleMates.setMateWeightMax(Convert.toInt(split[1], 0));
            }
            if (key.equals("mate_income")) {
                bcSingleMates.setMateIncome(Convert.toInt(value, 0));
                bcSingleMates.setMateIncomeCn(categoryCn);
            }
            if (key.equals("mate_education")) {
                bcSingleMates.setMateEducation(Convert.toInt(value, 0));
                bcSingleMates.setMateEducationCn(categoryCn);
            }
            if (key.equals("mate_district")) {
                bcSingleMates.setMateDistrict(value);
                bcSingleMates.setMateDistrictCn(categoryCn);
            }
            if (key.equals("mate_native_place")) {
                bcSingleMates.setMateNativePlace(value);
                bcSingleMates.setMateNativePlaceCn(categoryCn);
            }
            if (key.equals("mate_nationality")) {
                bcSingleMates.setMateNationality(Convert.toInt(value, 0));
                bcSingleMates.setMateNationalityCn(categoryCn);
            }
            if (key.equals("mate_disposition")) {
                bcSingleMates.setMateDisposition(Convert.toInt(value, 0));
                bcSingleMates.setMateDispositionCn(categoryCn);
            }
            if (key.equals("mate_marriage")) {
                bcSingleMates.setMateMarriage(Convert.toInt(value, 0));
                bcSingleMates.setMateMarriageCn(categoryCn);
            }
            if (key.equals("mate_children")) {
                bcSingleMates.setMateChildren(Convert.toInt(value, 0));
                bcSingleMates.setMateChildrenCn(categoryCn);
            }
            if (key.equals("mate_house")) {
                bcSingleMates.setMateHouse(Convert.toInt(value, 0));
                bcSingleMates.setMateHouseCn(categoryCn);
            }
            if (key.equals("mate_car")) {
                bcSingleMates.setMateCar(Convert.toInt(value, 0));
                bcSingleMates.setMateCarCn(categoryCn);
            }
            if (key.equals("mate_religious")) {
                bcSingleMates.setMateReligious(Convert.toInt(value, 0));
                bcSingleMates.setMateReligiousCn(categoryCn);
            }
            if (key.equals("mate_marry")) {
                bcSingleMates.setMateMarry(Convert.toInt(value, 0));
                bcSingleMates.setMateMarryCn(categoryCn);
            }
            if (key.equals("mate_family_backg")) {
                bcSingleMates.setMateFamilyBackg(Convert.toInt(value, 0));
                bcSingleMates.setMateFamilyBackgCn(categoryCn);
            }
            if (key.equals("mate_constellation")) {
                bcSingleMates.setMateConstellation(Convert.toInt(value, 0));
                bcSingleMates.setMateConstellationCn(categoryCn);
            }
            bcSingleMatesMapper.update(bcSingleMates, queryWrapper);
        } else {

            BcSingles bcSingles = new BcSingles();
            if (key.equals("nickname")) {
                bcSingles.setNickname(value);
            }
            if (key.equals("gender")) {
                bcSingles.setGender(Convert.toInt(value, 0));
                bcSingles.setGenderCn(categoryCn);
            }
            if (key.equals("district")) {
                bcSingles.setDistrict(value);
                bcSingles.setDistrictCn(categoryCn);
            }
            if (key.equals("birthday")) {
                bcSingles.setBirthday(Convert.toDate(value));
            }
            if (key.equals("height")) {
                bcSingles.setHeight(Convert.toInt(value, 0));
            }
            if (key.equals("income")) {
                bcSingles.setIncome(Convert.toInt(value, 0));
                bcSingles.setIncomeCn(categoryCn);
            }
            if (key.equals("education")) {
                bcSingles.setEducation(Convert.toInt(value, 0));
                bcSingles.setEducationCn(categoryCn);
            }
            if (key.equals("constellation")) {
                bcSingles.setConstellation(Convert.toInt(value, 0));
                bcSingles.setConstellationCn(categoryCn);
            }
            if (key.equals("zodiac")) {
                bcSingles.setZodiac(Convert.toInt(value, 0));
                bcSingles.setZodiacCn(categoryCn);
            }
            if (key.equals("blood")) {
                bcSingles.setBlood(Convert.toInt(value, 0));
                bcSingles.setBloodCn(categoryCn);
            }
            if (key.equals("weight")) {
                bcSingles.setWeight(Convert.toInt(value, 0));
            }
            if (key.equals("nationality")) {
                bcSingles.setNationality(Convert.toInt(value, 0));
                bcSingles.setNationalityCn(categoryCn);
            }
            if (key.equals("disposition")) {
                bcSingles.setDisposition(Convert.toInt(value, 0));
                bcSingles.setDispositionCn(categoryCn);
            }
            if (key.equals("house")) {
                bcSingles.setHouse(Convert.toInt(value, 0));
                bcSingles.setHouseCn(categoryCn);
            }
            if (key.equals("car")) {
                bcSingles.setCar(Convert.toInt(value, 0));
                bcSingles.setCarCn(categoryCn);
            }
            if (key.equals("industry")) {
                bcSingles.setIndustry(Convert.toInt(value, 0));
                bcSingles.setIndustryCn(categoryCn);
            }
            if (key.equals("profession")) {
                bcSingles.setProfession(Convert.toInt(value, 0));
                bcSingles.setProfessionCn(categoryCn);
            }
            if (key.equals("company")) {
                bcSingles.setCompany(value);
            }
            if (key.equals("school")) {
                bcSingles.setSchool(value);
            }
            if (key.equals("native_place")) {
                bcSingles.setNativePlace(value);
                bcSingles.setNativePlaceCn(categoryCn);
            }
            if (key.equals("family_backg")) {
                bcSingles.setFamilyBackg(Convert.toInt(value, 0));
                bcSingles.setFamilyBackgCn(categoryCn);
            }
            if (key.equals("marriage")) {
                bcSingles.setMarriage(Convert.toInt(value, 0));
                bcSingles.setMarriageCn(categoryCn);
            }
            if (key.equals("children")) {
                bcSingles.setChildren(Convert.toInt(value, 0));
                bcSingles.setChildrenCn(categoryCn);
            }
            if (key.equals("marry")) {
                bcSingles.setMarry(Convert.toInt(value, 0));
                bcSingles.setMarryCn(categoryCn);
            }
            if (key.equals("drink")) {
                bcSingles.setDrink(Convert.toInt(value, 0));
                bcSingles.setDrinkCn(categoryCn);
            }
            if (key.equals("smoking")) {
                bcSingles.setSmoking(Convert.toInt(value, 0));
                bcSingles.setSmokingCn(categoryCn);
            }
            if (key.equals("work_out")) {
                bcSingles.setWorkOut(Convert.toInt(value, 0));
                bcSingles.setWorkOutCn(categoryCn);
            }
            if (key.equals("work_rest")) {
                bcSingles.setWorkRest(Convert.toInt(value, 0));
                bcSingles.setWorkRestCn(categoryCn);
            }
            if (key.equals("pet")) {
                bcSingles.setPet(Convert.toInt(value, 0));
                bcSingles.setPetCn(categoryCn);
            }
            if (key.equals("religious")) {
                bcSingles.setReligious(Convert.toInt(value, 0));
                bcSingles.setReligiousCn(categoryCn);
            }
            if (key.equals("hobby[]")) {
                bcSingles.setHobby(value);
                bcSingles.setHobbyCn(categoryCn);
            }
            if (key.equals("soliloquy")) {
                bcSingles.setSoliloquy(value);
            }
            if (key.equals("photo_mode")) {
                bcSingles.setPhotoMode(Convert.toInt(value, 0));
            }
            if (key.equals("display_mode")) {
                bcSingles.setDisplayMode(Convert.toInt(value, 0));
            }
            if (key.equals("close")) {
                bcSingles.setIsClose(Convert.toInt(value, 0));
            }
            baseMapper.update(bcSingles, queryWrapper);
        }
        return true;
    }

    private String getCategoryName(String key, String value) {
        key = key.replace("[]", "");
        String categoryCn = "";
        if (key.equals("mate_district") ||
                key.equals("mate_native_place") ||
                key.equals("district") ||
                key.equals("native_place")) {
            //查询城市表
            if (StrUtil.isEmpty(value)) {
                return "";
            }
            if (value.equals("..")) {
                return "不限.不限.不限";
            }
            String[] cityArr = StrUtil.split(value, ".");
            List<BcCategoryDistricts> bcCategoryDistricts = bcCategoryDistrictsService.selectAllById(cityArr);
            for (String cityId :
                    cityArr) {

                BcCategoryDistricts cityData =
                        bcCategoryDistricts.stream().
                                filter(t -> t.getId().equals(Convert.toInt(cityId))).
                                findFirst().orElse(new BcCategoryDistricts());
                categoryCn += cityData.getName() + ".";
            }
            return StrUtil.removeSuffix(categoryCn, ".");
        }
        //查询分组表

        key = StrUtil.concat(false, "BC_", key);
        key = key.replace("mate_", "");
        List<BcCategorys> listCategory = bcCategorysService.selectByIds(value.split(","), key);
        if (null == listCategory || listCategory.size() <= 0) {
            return "";
        }
        List<String> collect = listCategory.stream().map(BcCategorys::getName).collect(Collectors.toList());
        return StrUtil.join(",", collect);
    }

    @Override
    public List<BcSingles> getOfficialRecommendation() {
        List<BcSingles> officialRecommendation = baseMapper.getOfficialRecommendation();
        if (null == officialRecommendation || officialRecommendation.size() <= 0) {
            return new ArrayList<>();
        }
        officialRecommendation.forEach(item -> {
            if (StrUtil.isEmpty(item.getPhoto())) {
                //添加默认图
                item.setPhoto("/m/img/avatar_default.png");
            } else {
                item.setPhoto(item.getPhoto() + "_200x200.jpg");
            }
        });
        return officialRecommendation;
    }

    @Override
    public List<BcSingles> getTodayRecommendation(String ids) {
        List<BcSingles> todayRecommendation = baseMapper.getTodayRecommendation(ids);
        if (null == todayRecommendation || todayRecommendation.size() <= 0) {
            return new ArrayList<>();
        }
        todayRecommendation.forEach(item -> {
            if (StrUtil.isEmpty(item.getPhoto())) {
                //添加默认图
                item.setPhoto("/m/img/avatar_default.png");
            } else {
                item.setPhoto(item.getPhoto() + "_200x200.jpg");
            }
        });
        return todayRecommendation;
    }

    @Override
    public String respToDayRecommendationInfo(List<BcSingles> list) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            BcSingles bcSingles = list.get(i);
            if (i % 4 == 0) {
                sb.append("<div class=\"lpage\">");
            }
            sb.append("<div class=\"item\">");
            sb.append("<a href=\"/m/single/info/" + bcSingles.getUserId() + "\">");
            sb.append(" <div class=\"photo \">");
//            String img = StrUtil.contains(bcSingles.getPhoto(), "avatar_default") ? bcSingles.getPhoto() : bcSingles.getPhoto() + "_200x200.jpg";
            sb.append("<img photo_mode=\"1\" bc-lazy-img=\"" + bcSingles.getPhoto() + "\" src=\"" + bcSingles.getPhoto() + "\">");
            sb.append("</div>");
            sb.append("<div class=\"nickname ellipsis\">");
            sb.append(bcSingles.getNickname());
            Integer gender = Convert.toInt(bcSingles.getGender(), 0);
            if (gender != 0) {
                sb.append(" <i class=\"gender_" + gender + "\"></i>");
            }
            sb.append(" <i class=\"icon_usergroup icon_usergroup_3\"></i>");
            sb.append("</div>");
            sb.append("<div class=\"info\">");
            sb.append(bcSingles.getAge() + "岁");
            sb.append("<span> . " + Convert.toInt(bcSingles.getHeight(), 160) + "cm</span>");
            sb.append("<span> . " + bcSingles.getEducationCn() + "</span></div>");
            sb.append(" <div class=\"info\">" + bcSingles.getDistrictCn() + "</div>");
            sb.append("</a></div>");
            if (i % 4 == 0) {
                sb.append("</div >");
            }
        }
        return sb.toString();
    }

    @Override
    public boolean isVip(UserInfo userInfo) {
        if (null == userInfo || Convert.toInt(userInfo.getId(), 0) <= 0) {
            return false;
        }
        //查询当前用户套餐
        BcSingles bcSingles = new BcSingles();
        bcSingles.setUserId(userInfo.getId());
        BcSingles bcSinglesResult = selectOne(bcSingles);
        if (null == bcSinglesResult || Convert.toInt(bcSinglesResult.getSetmealId(), 0) == 0) {
            return false;
        }
        //查询所有套餐
        List<BcSetmeals> bcSetmeals = bcSetmealsService.selectAll(null);
        //判断当前用户是否为不允许购买的套餐，如果是认为是免费客户
        long count = bcSetmeals.stream().filter(t ->
                t.getId().equals(bcSinglesResult.getSetmealId())
                        && t.getApply().equals(0)).count();
        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    public void updateBrowse(Integer userId) {
        baseMapper.updateBrowse(userId);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String aaaa= URLEncoder.encode("\"{\"module\":\"geolocation\",\"adcode\":110108,\"type\":\"ip\",\"nation\":\"中国\",\"province\":\"北京市\",\"city\":\"北京市\",\"district\":\"\",\"addr\":\"\",\"lat\":39.95933,\"lng\":116.29845,\"accuracy\":10000}\"", "utf-8");
        System.out.println(aaaa);
    }
    @Override
    public List<SingleSearchResponse> selectSingleSearch(Page page, SingleListRequest req,HttpServletRequest request) {
        //默认是新用户靠前
        String orderBy = " s.user_id desc";
        if (!StrUtil.isEmpty(req.getViewBy())) {
            if (req.getViewBy().equals("hot")) {
                //人气
                orderBy = " s.browse desc";
            } else if (req.getViewBy().equals("city")) {
//                orderBy = " s.id desc";
                String location = CookieUtils.getCookie(request, CookieConst.location);
                if(!StrUtil.isEmpty(location)){
                    JSONObject jsonObject = JSONUtil.parseObj(location);
                    NearbyRequest nearbyRequest = new NearbyRequest();
                    nearbyRequest.setLat(Convert.toStr(jsonObject.get("lat")));
                    nearbyRequest.setLng(Convert.toStr(jsonObject.get("lng")));
                    nearbyRequest.setCity(Convert.toStr(jsonObject.get("city")));
                    List<NearbyResponse> nearby = bcSingleLocationsService.nearby(page, nearbyRequest);
                    if (null != nearby && nearby.size()>0) {
                        List<Integer> userIdList = nearby.stream().map(x -> x.getUserId()).collect(Collectors.toList());
                        req.setUserIdList(userIdList);
                    }
                }
            } else if (req.getViewBy().equals("vip")) {
                orderBy = " s.setmeal_id desc";
            } else if (req.getViewBy().equals("auth")) {
                //查询实名制用户
                req.setIdentityCheck(1);
            }
        }
        req.setOrderBy(orderBy);
        if (!StrUtil.isEmpty(req.getAgeRand())) {
            String age = req.getAgeRand();
            String[] ageList = age.split("-");
            if (ageList.length > 1) {
                req.setMinAge(birthdayConvert(Convert.toInt(ageList[1])));
                req.setMaxAge(birthdayConvert(Convert.toInt(ageList[0])));
            }
        }
        if (!StrUtil.isEmpty(req.getHeightRand())) {
            String height = req.getHeightRand();
            String[] heightList = height.split("-");
            if (heightList.length > 1) {
                req.setMinHeight(Convert.toInt(heightList[0], 0));
                req.setMaxHeight(Convert.toInt(heightList[1], 0));
            }
        }
        if(!StrUtil.isEmpty(req.getDistrict())){
            req.setDistrict(districtConvert(req.getDistrict()));
        }
        if(!StrUtil.isBlank(req.getNativePlace())){
            req.setNativePlace(districtConvert(req.getNativePlace(),true));
        }

        List<SingleSearchResponse> singleSearchResponses = baseMapper.selectSingleSearch(page, req);

        //重写年龄
        singleSearchResponses.forEach(item -> {
            int age = 19;
            int bir = Convert.toInt(null == item.getBirthday() ? 0 : item.getBirthday().getYear(), 0);
            if (bir > 0) {
                age = Convert.toInt(new Date().getYear(), 0) - bir;
            }
            item.setAge(age);
        });
        return singleSearchResponses;
    }

    @Override
    public List<VoiceListResponse> selectVoiceList(Page page, VoiceListRequest req) {
        String orderBy = req.getOrderBy();
        //默认是新用户靠前
        String orderByStr = " s.setmeal_id desc";
        if (!StrUtil.isEmpty(orderBy)) {
            if (orderBy.equals("hot")) {
                //人气
                orderByStr = " s.browse desc";
            } else if (orderBy.equals("city")) {
                //TODO 如果是同城就去查坐标表
//                orderBy = " s.id desc";
            } else if (orderBy.equals("news")) {
                orderByStr = " s.user_id desc";
            }
        }
        req.setOrderBy(orderByStr);
        if (!StrUtil.isEmpty(req.getAge())) {
            String age = req.getAge();
            String[] ageList = age.split("~");
            if (ageList.length > 1) {
                int year = new Date().getYear();
                req.setMinAge(year - Convert.toInt(ageList[0], 0));
                req.setMaxAge(year - Convert.toInt(ageList[1], 0));
            }
        }
        List<VoiceListResponse> voiceListResponses = baseMapper.selectVoiceList(page, req);
        return voiceListResponses;
    }

    @Override
    public List<VideoListResponse> selectVideoList(Page page, VideoListRequest req) {
        String orderBy = req.getOrderBy();
        //默认是新用户靠前
        String orderByStr = " s.setmeal_id desc";
        if (!StrUtil.isEmpty(orderBy)) {
            if (orderBy.equals("hot")) {
                //人气
                orderByStr = " s.browse desc";
            } else if (orderBy.equals("city")) {
                //TODO 如果是同城就去查坐标表
//                orderBy = " s.id desc";
            } else if (orderBy.equals("news")) {
                orderByStr = " s.user_id desc";
            }
        }
        req.setOrderBy(orderByStr);
        if (!StrUtil.isEmpty(req.getAge())) {
            String age = req.getAge();
            String[] ageList = age.split("~");
            if (ageList.length > 1) {
                int year = new Date().getYear();
                req.setMinAge(year - Convert.toInt(ageList[0], 0));
                req.setMaxAge(year - Convert.toInt(ageList[1], 0));
            }
        }
        List<VideoListResponse> videoListResponses = baseMapper.selectVideoList(page, req);
        return videoListResponses;
    }

    @Override
    public List<MomenSingleResponse> selectMomenSingle(Set<Integer> userIds) {
        String userIdStr = StrUtil.join(",", userIds);
        if (StrUtil.isEmpty(userIdStr)) {
            return null;
        }
        List<MomenSingleResponse> list = baseMapper.selectMomenSingle(userIdStr);
        return list;
    }

    @Override
    public Integer ageConvert(Date birthday) {
        int age = 19;
        int bir = Convert.toInt(null == birthday ? 0 : birthday.getYear(), 0);
        if (bir > 0) {
            age = Convert.toInt(new Date().getYear(), 0) - bir;
        }
        return age;
    }
    @Override
    public Integer birthdayConvert(Integer age) {
        if (null == age || age.intValue()<=0) {
            return null;
        }
        String yyyy = DateUtil.offset(DateUtil.date(), DateField.YEAR, -1 * age).toString("yyyy");
        return Convert.toInt(yyyy);
    }

    @Override
    public String districtConvert(String district) {
        return this.districtConvert(district,false);
    }
    @Override
    public String districtConvert(String district,boolean fill) {
        if(StrUtil.isEmpty(district)){
            return null;
        }
        //如果需要补充最后一位
        if(fill){
            district=district+".";
        }
        //把所有逗号替换成点
        district=district.replace(",",".");

        //如果字符串是一个点或两个点，直接返回null
        if(district.equals("..") || district.equals(".")){
            return null;
        }
        //不是以两个点结尾，直接返回
        if(!district.endsWith("..")){
            return district;
        }
        //如果是以两个点结尾，把结尾的两个点替换成一个点
        return district.replace("..",".");
    }


    @Override
    public KarmaListResponse selectKarmaList(Integer page) {
        return baseMapper.selectKarmaList(page);
    }

    @Override
    public List<MomenSingleResponse> nearby(Page page, NearbyRequest req) {
        List<NearbyResponse> list = bcSingleLocationsService.nearby(page, req);
        //过滤重复且不包含自己的数据
        Set<NearbyResponse> nearbyList = list.stream().filter(t -> !t.getUserId().equals(req.getUserId()))
                .collect(Collectors.toSet());
        Set<Integer> userIds = nearbyList.stream().map(t -> t.getUserId()).collect(Collectors.toSet());
        if (null == userIds || userIds.size() <= 0) {
            return null;
        }
        String joinUserId = StrUtil.join(",", userIds);
        List<MomenSingleResponse> momenSingleResponses = baseMapper.selectMomenSingle(joinUserId);
        momenSingleResponses.forEach(item -> {
            NearbyResponse nearbyResponse = list.stream().
                    filter(t -> t.getUserId().equals(item.getUserId())).
                    findFirst().orElse(new NearbyResponse());
            item.setDistance(nearbyResponse.getDistance());
            item.setAge(ageConvert(item.getBirthday()));
        });
        return momenSingleResponses;
    }

    @Override
    public boolean pcModify(HttpServletRequest request,
                            HttpServletResponse response,
                            BcSingles req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", req.getUserId());
        if (!StrUtil.isEmpty(req.getPhoto())) {
            //有待审核的头象
            req.setIsAuth(1);
            req.setPhotoCheck(3);
            req.setPhotoAt(new Date());
        }
        baseMapper.update(req, queryWrapper);
        //重新登录，需要把头象写到cookie里
        BcUsers byId = bcUsersService.getById(req.getUserId());
        bcUsersService.login(request, response, byId);
        return false;
    }

    @Override
    public boolean removeShow(BcSingles req) {
        return baseMapper.removeShow(req);
    }


    /**
     * 推荐好友编码
     * */
    @Override
    public String getEidEncode(String encodeEid) {
        try {
            String s = AES.aesEncrypt(encodeEid);
            String encode = Base64.encode(s);
            return encode;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 推荐好友解码
     * */
    @Override
    public String getEidDecode(String decodeEid) {
        try {
            String decodeStr = Base64.decodeStr(decodeEid);
            String s = AES.aesDecrypt(decodeStr);
            return s;
        } catch (Exception e) {
            return "";
        }
    }

    @Override
    public TeamCountResponse getTeamCount(Integer userId) {
      return   baseMapper.getTeamCount(userId);
    }

    @Override
    public List<SingleSearchResponse> mayLike(UserInfo userInfo, HttpServletRequest request) {
        SingleListRequest req = new SingleListRequest();
        Page page = new Page();
        page.setCurrent(1);
        page.setSize(20);
        return this.selectSingleSearch(page, req, request);
    }
}
